<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('新增拜访日志')"/>
    <th:block th:include="include :: datetimepicker-css"/>
    <th:block th:include="include :: bootstrap-fileinput-css"/>
    <title></title>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-visit_log-add">
        <div class="form-group" id="unit3Li" style="display: none">
            <label class="col-sm-3 control-label is-required" for="unit3Select">三级单元：</label>
            <div class="col-sm-8">
                <select class="form-control"
                        id="unit3Select"
                        onchange="setNextUnitSelect(this.value, 3)"
                        required>
                </select>
            </div>
        </div>
        <div class="form-group" id="unit4Li" style="display: none">
            <label class="col-sm-3 control-label is-required" for="unit4Select">四级单元：</label>
            <div class="col-sm-8">
                <select class="form-control"
                        id="unit4Select"
                        onchange="setNextUnitSelect(this.value, 4)"
                        required>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label is-required" for="unit5Select">包区名称：</label>
            <div class="col-sm-8">
                <select class="form-control"
                        id="unit5Select"
                        onchange="setSubordinateSelect(this.value,5)"
                        required>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label is-required" for="unit6Select">社区/行政村：</label>
            <div class="col-sm-8">
                <select class="form-control"
                        id="unit6Select"
                        onchange="setSubordinateSelect(this.value,6)"
                        required>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label is-required" for="unit7Select" id="unit7Label">小区/街道/自然庄：</label>
            <div class="col-sm-8">
                <select class="form-control"
                        id="unit7Select"
                        name="unit7Id"
                        onchange="setSubordinateSelect(this.value,7,this)"
                        required>
                </select>
            </div>
        </div>
        <div class="form-group" id="unit8Div" style="display: none">
            <label class="col-sm-3 control-label is-required" for="unit8Select">楼栋名称：</label>
            <div class="col-sm-8">
                <select class="form-control"
                        id="unit8Select"
                        onchange="setSubordinateSelect(this.value,8,'#unit7Select')"
                        required>
                </select>
            </div>
        </div>
        <div class="form-group" id="unit9Div" style="display: none">
            <label class="col-sm-3 control-label is-required" for="unit9Select">单元名称：</label>
            <div class="col-sm-8">
                <select class="form-control"
                        id="unit9Select"
                        name="unit9Id"
                        required>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label is-required" for="userType">用户类型：</label>
            <div class="col-sm-8">
                <select class="form-control" id="userType" name="communicationOperator"
                        onchange="setExpiredTimeSelectRequired(this.value)" required
                        th:with="type=${@dict.getType('communication_operators')}">
                    <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"></option>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label is-required" for="userName">用户姓名：</label>
            <div class="col-sm-8">
                <input class="form-control" id="userName" maxlength="20" name="userName" required type="text">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label is-required" for="currentPhoneNumber">当前号码：</label>
            <div class="col-sm-8">
                <div class="input-group">
                    <input class="form-control" id="currentPhoneNumber" maxlength="11" name="currentPhoneNumber"
                           placeholder="请输入手机号码" required type="text">
                    <span class="input-group-addon"><i class="fa fa-mobile"></i></span>
                </div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label is-required" for="mealValue">套餐价值：</label>
            <div class="col-sm-8">
                <input class="form-control" id="mealValue" name="mealValue" required type="number">
            </div>
        </div>
        <div class="form-group" id="expiredTimeDiv">
            <label class="col-sm-3 control-label" for="expiredTimeInput" id="expiredTimeLabel">到期时间：</label>
            <div class="col-sm-8">
                <div class="input-group date">
                    <input class="form-control"
                           id="expiredTimeInput"
                           name="expiredTime"
                           placeholder="yyyy-MM-dd"
                           type="text">
                    <span class="input-group-addon">
                        <i class="fa fa-calendar"></i>
                    </span>
                </div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label" for="translatedPhoneNumber">转化号码：</label>
            <div class="col-sm-8">
                <div class="input-group">
                    <input class="form-control" id="translatedPhoneNumber" maxlength="11"
                           name="translatedPhoneNumber"
                           placeholder="请输入手机号码" type="text">
                    <span class="input-group-addon"><i class="fa fa-mobile"></i></span>
                </div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label is-required">现场照片：</label>
            <div class="col-sm-8">
                <input name="scenePhoto" required type="hidden">
                <div class="file-loading">
                    <input accept="image/*" class="form-control file-upload" id="scenePhoto" name="file" type="file">
                </div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label" for="remake">备注：</label>
            <div class="col-sm-8">
                <textarea class="form-control" id="remake" name="remake"></textarea>
            </div>
        </div>
    </form>
</div>
<th:block th:include="include :: footer"/>
<th:block th:include="include :: datetimepicker-js"/>
<th:block th:include="include :: bootstrap-fileinput-js"/>
<script th:inline="javascript">
    let prefix = ctx + "workbench/visit_log"
    $("#form-visit_log-add").validate({
        focusCleanup: true,
        onkeyup: false,
        rules: {
            currentPhoneNumber: {
                isPhone: true,
                remote: {
                    url: prefix + "/checkPhoneNumberUnique",
                    type: "post",
                    dataType: "json",
                    data: {
                        type: '',
                        phoneNumber: function () {
                            return $.common.trim($("#currentPhoneNumber").val());
                        }
                    },
                    dataFilter: function (data, type) {
                        return $.validate.unique(data);
                    }
                }
            },
            translatedPhoneNumber: {
                isPhone: true,
                remote: {
                    url: prefix + "/checkPhoneNumberUnique",
                    type: "post",
                    dataType: "json",
                    data: {
                        type: '1',
                        phoneNumber: function () {
                            return $.common.trim($("#translatedPhoneNumber").val());
                        }
                    },
                    dataFilter: function (data, type) {
                        return $.validate.unique(data);
                    }
                }
            }
        },
        messages: {
            "currentPhoneNumber": {
                remote: "手机号码已经录入"
            },
            "translatedPhoneNumber": {
                remote: "手机号码已经转化"
            },
        }
    });

    /**
     * 设置过期时间是否必填，异网用户必填，本网用户和潜在用户可填可不填
     */
    function setExpiredTimeSelectRequired(value) {
        let expiredTimeInput = document.getElementById('expiredTimeInput')
        if (value === '6') {
            $('#expiredTimeLabel').addClass('is-required')
            expiredTimeInput.setAttribute('required', 'required')
        } else {
            $('#expiredTimeLabel').removeClass('is-required')
            expiredTimeInput.removeAttribute('required')
        }
        $("#expiredTimeDiv").selectpicker('refresh')
    }

    function submitHandler() {
        if ($('#currentPhoneNumber').val() === $('#translatedPhoneNumber').val()) {
            $.modal.alertError('转化号码不能与当前号码相同');
            return
        }
        if ($.validate.form()) {
            let unit7Select = $('#unit7Select')
            let visitLogIdSelect
            //获取当前七级单元是否是小区
            let unit7Type = unit7Select.find("option:selected").attr("unit7Type");
            let data = $('#form-visit_log-add').serialize()
            //如果是小区,信息上报的关联id设置成单元id
            if (unit7Type !== null && unit7Type === '0') {
                visitLogIdSelect = $('#unit9Select')
                let tempStr = data.substring(data.indexOf('='), data.indexOf('unit9Id') + 7)
                data = data.replace(tempStr, '')
            } else {
                visitLogIdSelect = unit7Select
                data = data.replace('&unit9Id=', '')
            }
            if (visitLogIdSelect.val() === '') {
                $.modal.alertWarning("请先在所辖村庄中添加自然庄/街道/小区");
                return;
            }
            $.operate.save(prefix + "/add", data);
        }
    }

    $("input[name='expiredTime']").datetimepicker({
        format: "yyyy-mm-dd",
        minView: "month",
        autoclose: true
    });

    $(".file-upload").fileinput({
        uploadUrl: ctx + 'common/upload',
        maxFileCount: 5,
        autoReplace: true,
        allowedFileTypes: ['image'],
        allowedPreviewTypes: ['image'],
        // allowedFileExtensions: ['image']
    }).on('fileuploaded', function (event, data) {
        let inputSelector = $("input[name='" + event.currentTarget.id + "']");
        let images = inputSelector.val();
        if (images === '') {
            images = data.response.url;
        } else {
            images = images + ',' + data.response.url;
        }
        inputSelector.val(images)
    }).on("filebatchselected", function () {
        // 文件选择完直接调用上传方法。
        $(this).fileinput("upload");
    }).on('fileremoved', function (event) {
        isUpload = false;
        $("input[name='" + event.currentTarget.id + "']").val('')
    })

    $(function () {
        $.ajax({
            method: 'post',
            url: '/workbench/leaf_unit_city/getMyDept',
            success: function (dept) {
                let level = dept.level;
                if (level !== 2) {
                    setPreviousUnitSelect(dept.parentId, level);
                }
                setCurrentSelect(dept, level);
                if (level <= 4) {
                    setNextUnitSelect(dept.deptId, level);
                } else {
                    setSubordinateSelect(dept.deptId, level)
                }
            }
        })
    })

    /**
     * 设置上级单元选择器
     * @param parentId 当前选择的项
     * @param currentLevel 单元等级
     */
    function setPreviousUnitSelect(parentId, currentLevel) {
        $.ajax({
            method: 'post',
            url: '/system/dept/selectByDeptId',
            data: {
                deptId: parentId
            },
            success: function (previousUnit) {
                let parentLevel = currentLevel - 1
                let selectId
                switch (parentLevel) {
                    case 5:
                        selectId = "#unit5Select"
                        setPreviousUnitSelect(previousUnit.parentId, parentLevel)
                        break
                    case 4:
                        selectId = "#unit4Select"
                        setPreviousUnitSelect(previousUnit.parentId, parentLevel)
                        break
                    case 3:
                        selectId = "#unit3Select"
                        break
                    case 2:
                        break
                    default:
                        alert("单元等级错误p：" + parentLevel)
                }
                let option = "<option value='" + previousUnit.deptId + "'>" + previousUnit.deptName + "</option>"
                $(selectId).html(option).selectpicker('refresh');
            }
        })
    }

    /**
     * 设置当前选择器的值
     */
    function setCurrentSelect(dept, level) {
        let selectId
        switch (level) {
            case 9:
                selectId = "#unit9Select"
                break
            case 8:
                selectId = "#unit8Select"
                break
            case 7:
                selectId = "#unit7Select"
                break
            case 6:
                selectId = "#unit6Select"
                break
            case 5:
                selectId = "#unit5Select"
                break
            case 4:
                selectId = "#unit4Select"
                break
            case 3:
                selectId = "#unit3Select"
                break
            case 2:
                break
            default:
                alert("单元等级错误")
        }
        let options = "<option value='" + dept.deptId + "'>" + dept.deptName + "</option>";
        $(selectId).html(options).selectpicker('refresh');
    }

    /**
     * 设置3,4单元的下级单元选择器
     * @param deptId 本单元id
     * @param parentLevel 本单元等级
     */
    function setNextUnitSelect(deptId, parentLevel) {
        let currentLevel = parentLevel + 1
        resetCurrentSelectOptions(currentLevel)
        $.ajax({
            method: 'post',
            url: '/system/dept/getChildrenDeptFilterByTypes',
            data: {
                deptId: deptId,
                types: '1,2,3',
            },
            success: function (list) {
                let options = "";
                for (let i = 0; i < list.length; i++) {
                    let option = list[i];
                    options += "<option value='" + option.deptId + "'>" + option.deptName + "</option>";
                }
                let selectId
                let liId
                let firstUnit = list[0]
                switch (currentLevel) {
                    case 5:
                        selectId = "#unit5Select"
                        if (firstUnit !== undefined) {
                            setSubordinateSelect(list[0].deptId, currentLevel)
                        }
                        break
                    case 4:
                        selectId = "#unit4Select"
                        liId = "#unit4Li"
                        if (firstUnit !== undefined) {
                            setNextUnitSelect(list[0].deptId, currentLevel)
                        }
                        break
                    case 3:
                        selectId = "#unit3Select"
                        liId = "#unit3Li"
                        if (firstUnit !== undefined) {
                            setNextUnitSelect(list[0].deptId, currentLevel)
                        }
                        break
                    default:
                        alert("单元等级错误n：" + parentLevel)
                }
                $(selectId).html(options).selectpicker('refresh');
                if (liId !== '') {
                    $(liId).show();
                }
            }
        })
    }

    /**
     * 设置下属选择器
     * @param parentId parentId
     * @param parentLevel parentLevel
     * @param unit7Select unit7Select
     */
    function setSubordinateSelect(parentId, parentLevel, unit7Select) {
        if (parentLevel === 7) {
            let unit7Type = $(unit7Select).find("option:selected").attr("unit7Type");
            let unit7Name;
            switch (unit7Type) {
                case '0':
                    unit7Name = '小区名称：';
                    break;
                case '1':
                    unit7Name = '街道名称：';
                    break;
                case '2':
                    unit7Name = '自然庄名称：';
                    break;
                default:
                    unit7Name = '小区/街道/自然庄：';
            }

            $('#unit7Label').html(unit7Name);
        }
        let currentLevel = parentLevel + 1
        resetCurrentSelectOptions(currentLevel)
        $.ajax({
            method: 'post',
            url: '/workbench/leaf_unit_city/selectChildrenUnitByParentId',
            data: {
                parentId: parentId,
                currentLevel: currentLevel
            },
            success: function (list) {
                let options = "";
                let unit7Name;
                for (let i = 0; i < list.length; i++) {
                    let option = list[i];
                    if (i === 0 && currentLevel === 7) {
                        switch (option.unit7Type) {
                            case 0:
                                unit7Name = '小区名称：';
                                break;
                            case 1:
                                unit7Name = '街道名称：';
                                break;
                            case 2:
                                unit7Name = '自然庄名称：';
                                break;
                            default:
                                unit7Name = '小区/街道/自然庄：';
                        }
                    }
                    options += "<option unit7Type=" + option.unit7Type + " value='" + option.id + "'>" + option.name + "</option>";
                }
                options = options.length === 0 ? "<option value=\"\">区域不存在，请在社区/行政村管理中添加</option>" : options;
                let unitSelect
                let firstItem = list[0]
                switch (currentLevel) {
                    case 6:
                        unitSelect = '#unit6Select'
                        if (firstItem !== undefined) {
                            setSubordinateSelect(firstItem.id, currentLevel);
                        } else {
                            $('#unit7Select').html(options).selectpicker('refresh');
                        }
                        break
                    case 7:
                        unitSelect = '#unit7Select';
                        if (firstItem !== undefined) {
                            setSubordinateSelect(firstItem.id, currentLevel, unitSelect)
                        } else {
                            $('#unit8Select').html(options).selectpicker('refresh');
                        }
                        break
                    case 8:
                        if (firstItem !== undefined) {
                            setSubordinateSelect(firstItem.id, currentLevel)
                        } else {
                            $('#unit9Select').html(options).selectpicker('refresh');
                        }
                        let unit7Type = $(unit7Select).find("option:selected").attr("unit7Type");
                        if (unit7Type === '0') {
                            $('#unit8Div').show()
                            $('#unit9Div').show()
                        } else {
                            $('#unit8Div').hide()
                            $('#unit9Div').hide()
                        }
                        unitSelect = '#unit8Select';
                        break
                    case 9:
                        unitSelect = '#unit9Select'
                        break
                    default:
                        console.log('ss' + currentLevel)
                        return
                }
                $(unitSelect).html(options).selectpicker('refresh');
                if (unit7Name !== undefined) {
                    $('#unit7Label').html(unit7Name);
                }
            }
        });
    }

    /**
     * 根据当前level重置当前选择器
     * @param currentLevel
     */
    function resetCurrentSelectOptions(currentLevel) {
        let options = "<option value=\"\">区域不存在，请在社区/行政村管理中添加</option>";
        switch (currentLevel) {
            case 3:
                $("#unit3Select").html(options).selectpicker('refresh');
                resetCurrentSelectOptions(currentLevel + 1);
                break;
            case 4:
                $("#unit4Select").html(options).selectpicker('refresh');
                resetCurrentSelectOptions(currentLevel + 1);
                break;
            case 5:
                $("#unit5Select").html(options).selectpicker('refresh');
                resetCurrentSelectOptions(currentLevel + 1);
                break;
            case 6:
                $("#unit6Select").html(options).selectpicker('refresh');
                resetCurrentSelectOptions(currentLevel + 1);
                break;
            case 7:
                $("#unit7Select").html(options).selectpicker('refresh');
                resetCurrentSelectOptions(currentLevel + 1);
                break;
            case 8:
                $("#unit8Select").html(options).selectpicker('refresh');
                resetCurrentSelectOptions(currentLevel + 1);
                break;
            case 9:
                $("#unit9Select").html(options).selectpicker('refresh');
                break;
            default:
                alert('mm' + currentLevel)
        }
    }
</script>
</body>
</html>
